//数据埋点

function getCannel() {
  return getApp().globalData.channel || "";
}

function getSource() {
  return getApp().globalData.source || "";
}

function setGlobalData(params) {
  if (params.channel || params.source) {
    getApp().globalData.channel =
      getApp().globalData.channel || params.channel || "";
    getApp().globalData.source =
      getApp().globalData.source || params.source || "";
    return true;
  } else {
    //如果链接有channel，但是值为空，也不修改
    if (params.hasOwnProperty("channel") || params.hasOwnProperty("source")) {
      return true;
    }
    return false;
  }
}

export const coverTrack = (sensors) => {
  const track = sensors.track;
  sensors.track = (eventName, params = {}) => {
    params.channel = params.channel || getCannel();
    params.source = params.source || getSource();
    if ('$MPClick' == eventName) {
      if (!params[`$element_name`] && !params[`$element_content`]) {
        return;
      }
    }
    track(eventName, params);
  };
};

const urlCanAdd = (url) => {
  if (url.indexOf("source=") >= 0 || url.indexOf("channel=") >= 0) {
    return false;
  }
  return true;
};

const sourceAndChannel = () => {
  let parms = {};
  if (getSource()) {
    parms["source"] = getSource();
  }
  if (getCannel()) {
    parms["channel"] = getCannel();
  }
  return Object.keys(parms)
    .map((key) => `${key}=${parms[key]}`)
    .join("&");
};

export const repairUrl = (url) => {
  let finalUrl = url;
  if (finalUrl.indexOf("%2F%2F") >= 0) {
    finalUrl = decodeURIComponent(finalUrl);
  }
  if (finalUrl.indexOf("%") >= 0) {
    //如果有不识别的字符串，不加处理了，直接返回
    return url;
  }
  const urlSplit = finalUrl.split("#");
  const index = (urlSplit[1] || urlSplit[0]).indexOf("?");
  if (index >= 0) {
    const paramArray = (urlSplit[1] || urlSplit[0])
      .substr(index + 1)
      .split("&");
    const params = {};
    for (let i = 0; i < paramArray.length; i++) {
      let p = paramArray[i].split("=");
      params[p[0]] = p[1];
    }
    if (!setGlobalData(params) && urlCanAdd(finalUrl)) {
      finalUrl = `${url}&${sourceAndChannel()}`;
    }
  } else {
    finalUrl = `${url}?${sourceAndChannel()}`;
  }
  // console.log('-repairUrl-',url,finalUrl)
  return finalUrl;
};
